package common;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * MessageManager sends and receives messages over
 * the given socket.
 * 
 * @author Lukasz
 *
 */

public class ConnectionManager {
	
	private Socket socket = null;
	
	private ObjectInputStream in = null;
	private ObjectOutputStream out = null;
	
	private boolean enabled = true;
	
	public ConnectionManager(Socket socket) {
		this.socket = socket;
	}
	
	public Socket getSocket() {
		return socket;
	}
	
	public synchronized boolean sendMessage(ControlMessage msg) {
		System.out.println("send1");
		
		if (out == null)
			try {
				this.out = new ObjectOutputStream(socket.getOutputStream());
				this.out.flush();
			} catch (IOException e) {
				//e.printStackTrace();
				return false;
			}
		
		try {
			out.writeObject(msg);
			out.flush();
		} catch (IOException e) {
			//e.printStackTrace();
			System.out.println("send2");
			return false;
		}
		
		System.out.println("send3");
		return true;
	}
	
	public Message receiveMessage() {
		System.out.println("rec1");
		Object o = null;
		Message msg = null;
		
		if (in == null)
			try {
				this.in = new ObjectInputStream(socket.getInputStream());
			} catch (IOException e) {
				//e.printStackTrace();
				return null;
			}
		
		try {
			o = in.readObject();
			msg = (Message) o;
		} catch (ClassCastException ce) {
			if (o != null)
				msg = new Message((ControlMessage) o, false);
		} catch (Exception e) {
			//e.printStackTrace();
			System.out.println("in.readObject exception!");
			return null;
		}
		
		System.out.println("rec3");
		return msg;
	}
	
	public void close() {
		System.out.println("close1");
		try {
			in.close();
			out.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		in = null;
		out = null;
		socket = null;
		System.out.println("close2");
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public boolean isEnabled() {
		return enabled;
	}
}
